package com.foreveross.proxyip.core.zk.task.strategy;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mortbay.log.Log;

import com.foreveross.proxyip.core.pools.AvailablePool;
import com.foreveross.proxyip.core.redis.RedisExecutor;
import com.foreveross.proxyip.core.zk.task.ZkTask;
import com.foreveross.proxyip.core.zk.task.doLoad.IDoLoad;
import com.foreveross.proxyip.entity.ProxyIpBean;

public class DoloadTask extends ZkTask {

	public final static String className = "DoloadTask";
	
	
	@Override
	public int exec(Long[] taskNum,String taskParams) throws Exception {
		log.info("ip下载任务, taskNum:{}, taskParams:{}", taskNum, taskParams);
		
		Long currtime = System.currentTimeMillis();
		final AvailablePool pool = getPool(taskParams);
		IDoLoad doLoad = (IDoLoad)pool;
		List <ProxyIpBean> list = doLoad.download(taskNum[0]);//这个应用下载的ip
		 for(int i=0;i<list.size();i++){
//			 try{
				 final ProxyIpBean ipBean = list.get(i);
				 if(StringUtils.isBlank(ipBean.getIp())){
					 continue;
				 }
//			 jedis = pool.redisManager.getJedis();
			 
			 new RedisExecutor<Boolean>() {
					@Override
					public Boolean run() throws Exception {
						 tran = jedis.multi();
						 pool.ipStoreMap.set(tran,ipBean.getCompletionIP(),ipBean);
						 redisManager.lPush(tran,CheckInTask.getSourceKey(pool), ipBean.getCompletionIP());//准备验证的ip,推入任务,准备
						 tran.exec();
						 return null;
					}
				}.exec();
			 
			
//			 tran = jedis.multi();
//			 pool.ipStoreMap.set(tran,ipBean.getIp(),ipBean);
//			 redisManager.lPush(tran,CheckInTask.getSourceKey(pool), ipBean.getIp());//准备验证的ip,推入任务,准备
//			 tran.exec();
			
//			 }catch(Exception e){
//				 e.printStackTrace();
//				 if(tran!=null)tran.discard();
//				 pool.redisManager.getJedisPool().returnBrokenResource(jedis);
//			 }finally{
//				 if(jedis!=null)pool.redisManager.getJedisPool().returnResource(jedis);
//			 }
		 }
		 
		 Log.info("doloadTask :" + CheckInTask.getSourceKey(pool) + list.size() + " need download "+taskNum[0]+", actually,spend time :"+(System.currentTimeMillis()-currtime));
		return 1;
	}


	@Override
	public boolean breakTask(String taskParams) throws Exception {
		AvailablePool pool = getPool(taskParams);
		if(this.redisManager.len(CheckInTask.getSourceKey(pool))>=pool.getProxyMax()){//缓存池满了停止执行了.
			return true;
		}
		return false;
	}
	
}
